package com.app.micaihu.custom.components.downandupload;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.game.IDownload;
import com.app.micaihu.bean.infor.GetTaskBean;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.view.camera.utils.DialogUtils;
import com.app.micaihu.view.main.game.GameDownloadActivity;
import com.app.micaihu.view.utils.DownloadAgainUtils;
import com.app.okhttplib.HttpInfo;
import com.app.okhttplib.OkHttpUtil;
import com.app.okhttplib.annotation.DownloadStatus;
import com.app.okhttplib.bean.DownloadFileInfo;
import com.app.okhttplib.callback.OnDownloadingCallback;
import com.app.okhttplib.callback.ProgressCallback;
import com.app.okhttplib.helper.DownUpLoadHelper;
import com.app.okhttplib.util.AppUtils;
import com.app.okhttplib.util.EncryptUtil;
import com.app.utils.util.ToastUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import vip.ruoyun.helper.avoid.AvoidOnResultHelper;

import static android.app.Activity.RESULT_OK;
import static com.umeng.socialize.utils.ContextUtil.getPackageName;

/**
 * Created by Guo on 2017/6/8.
 */

public class LoadingView extends FrameLayout implements OnDownloadingCallback, View.OnClickListener {

    private IDownload iDownload;//当前View 所持有的下载info
    private FrameLayout container;
    private TextView prompt;
    private ProgressBar progress;

    private String open = "打开";
    private String download = "下载";
    private String install = "安装";
    private String continues = "继续";
    private String prepareing = "等待中...";
    private String noExist = "已下架";
    private int bgDefault;
    private int bgComplete;
    private int bgLoading;
    private int textSize;
    private int textColorDefault;
    private int textColorLoading;
    private int textColorComplete;

    private float percent = 0.0f;

    public LoadingView(Context context) {
        this(context, null);
    }

    public LoadingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }


    private Observer<HashMap> observer = new Observer<HashMap>() {
        @Override
        public void onChanged(@Nullable HashMap s) {
            String iTag = iDownload.getITag();
            String url = (String) s.get(Config.Extra.url);
            String progress = (String) s.get(Config.Extra.progress);
            if (iTag.equals(OkHttpUtil.getTag(url))) {
                LoadingView.this.onLoading(iTag, Float.parseFloat(progress));
            }
        }
    };


    private void init(Context context, AttributeSet attrs) {
        LiveEventBus.get(Config.EventBus.gameDownLoad, HashMap.class).observeForever(observer);
        inflate(context, R.layout.view_loading, this);
        container = (FrameLayout) findViewById(R.id.bg);
        prompt = findViewById(R.id.prompt);
        progress = (ProgressBar) findViewById(R.id.progress);

        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.LoadingView);
            if (typedArray != null) {
                //背景,两种,1:未下在;2:下载完成
                bgDefault = typedArray.getResourceId(R.styleable.LoadingView_bgDefault, 0);
                bgComplete = typedArray.getResourceId(R.styleable.LoadingView_bgComplete, 0);
                //进度条
                bgLoading = typedArray.getResourceId(R.styleable.LoadingView_bgLoading, 0);

                //字体,未下载,下载中,完成状态
                textSize = typedArray.getDimensionPixelSize(R.styleable.LoadingView_innerTextSize, 32);

                textColorDefault = typedArray.getColor(R.styleable.LoadingView_textColorDefault, 0);
                textColorLoading = typedArray.getColor(R.styleable.LoadingView_textColorLoading, 0);
                textColorComplete = typedArray.getColor(R.styleable.LoadingView_textColorComplete, 0);

                typedArray.recycle();
            }
        }
        if (textSize > 0) {
            prompt.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        }
        if (bgLoading != 0) {
            progress.setProgressDrawable(AppApplication.getInstance().getResources().getDrawable(bgLoading));
        }


    }

    /**
     * 必做的一步,为当前的view 设置下载数据
     *
     * @param tag
     */
    @Override
    public void setTag(Object tag) {
        super.setTag(tag);
        if (tag != null && tag instanceof IDownload) {
            LogUtils.e("getViewTag", "--->" + ((IDownload) tag).getStatus());
            if (((IDownload) tag).getStatus() == 4) {
                ViewSet(NoExist, 0);
                return;
            }

            //判断,如果View服用并且 被重设,则将当前的callback 移除掉
            if (iDownload != null && iDownload != (IDownload) tag) {
                DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag());
                if (downloadFileInfo != null) {
                    downloadFileInfo.removeViewCallback(this);
                }
            }
            iDownload = (IDownload) tag;
            setOnClickListener(this);
        } else {
            //防止 View 服用的时候 显示不正确
            iDownload = null;
            setOnClickListener(null);
        }
        ViewSet(INIT, 0);
        if (iDownload == null) return;//如果为null.则显示默认状态
        //首先判断是否安装了
        boolean isinstall = com.blankj.utilcode.util.AppUtils.isAppInstalled(iDownload.getIPackageName());
//        boolean isinstall = AppUtils.isinstall(getContext(), iDownload.getIPackageName());
        if (isinstall) {//经安装过了-可以直接打开
            //显示开启游戏
            ViewSet(OPEN, 0);
        } else {//没有安装
            //获取当前的文件夹中的文件.
            //如果当前有完整的文件,但是没有安装,将其放入到安装的listener中.监听安装
            File unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, iDownload.getIPath() + ".apk");
            if (unInstallFile.exists() && unInstallFile.isFile()) {
                //现在是已下载完成,准备安装
                ViewSet(INSTALL, 100);
                DownloadUtils.getSingleton().putInstallCallBack(iDownload.getIPackageName(), this);
                return;
            }
            //如果是下载中或者未下载的话,先从下载的listener 中找
            DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag());
            //如果没有.则新建一个 add 到下载的listener 中去,并设置相应的参数
            if (downloadFileInfo == null) {
                DownloadFileInfo downloadFileInfoInit = new DownloadFileInfo(iDownload.getIUrl(), iDownload.getIPath(), new ProgressCallback() {
                    @Override
                    public void onProgressMain(float percent, long bytesWritten, long contentLength, boolean done, String tag) {

                        DownloadFileInfo downloadFileInfoTemp = DownloadUtils.getSingleton().getDownloadFileInfo(tag);
                        if (downloadFileInfoTemp != null) {
                            List<OnDownloadingCallback> viewCallbackList = downloadFileInfoTemp.getViewCallbackList();
                            if (viewCallbackList != null && viewCallbackList.size() > 0) {
                                for (OnDownloadingCallback onDownloadingCallback : viewCallbackList) {
                                    if (onDownloadingCallback != null) {
                                        onDownloadingCallback.onLoading(tag, percent);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onResponseMain(String filePath, HttpInfo info) {
                        DownloadFileInfo downloadFileInfoTemp = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(info.getUrl()));
                        if (downloadFileInfoTemp != null) {
                            List<OnDownloadingCallback> viewCallbackList = downloadFileInfoTemp.getViewCallbackList();

//                            File file = new File(downloadFileInfoTemp.getSaveFileDir(), downloadFileInfoTemp.getSaveFileName());
                            if (viewCallbackList != null && viewCallbackList.size() > 0) {
                                if (info.isSuccessful()) {
                                    ToastUtils.makeText("下载完成");
                                    //下载完成统计
                                    DownloadUtils.getSingleton().requestStatisticsInterface(iDownload.getIGameId(), DownloadUtils.CLICKTYPE_DOWNLOADCOMPLETED);
                                } else if (info.getRetCode() == HttpInfo.LoadingPause) {
                                    ToastUtils.makeText("暂停下载");
                                } else if (info.getRetCode() == HttpInfo.RequestCancle) {
                                    ToastUtils.makeText("取消下载");
                                    cancelAfterOpration(info, downloadFileInfoTemp);
                                } else {//其他,直接弹message的error
//                                    ToastUtils.makeText(info.getRetDetail());
                                    ViewSet(PAUSE, percent);
                                }

                                for (int i = 0; i < viewCallbackList.size(); i++) {
                                    OnDownloadingCallback onDownloadingCallback = viewCallbackList.get(i);
                                    if (onDownloadingCallback != null) {
                                        //不仅要判断返回码,还需要判断本地文件是否存在
                                        if (info.isSuccessful()
//                                               &&  file.exists() && file.isFile()
                                        ) {//下载成功的回调
                                            onDownloadingCallback.onComlpeted(OkHttpUtil.getTag(info.getUrl()), info);
                                        } else if (info.getRetCode() == HttpInfo.RequestCancle) {
                                            onDownloadingCallback.onInit(OkHttpUtil.getTag(info.getUrl()));
                                        } else {//错误的回调
                                            if (info.getRetCode() != HttpInfo.SUCCESS) {
                                                if (info.getRetCode() != HttpInfo.RequestCancle) {
                                                    onDownloadingCallback.onPause(OkHttpUtil.getTag(info.getUrl()),
                                                            downloadFileInfoTemp.getPercent());
                                                    downloadFileInfoTemp.setDownloadStatus(DownloadStatus.PAUSE);

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                //设置下载的目录
                downloadFileInfoInit.setSaveFileDir(DownloadUtils.DOWNLOAD_FILEDIR);

                //判断是否是未下载完成的
                String unCompletedFile = "";
                try {
                    unCompletedFile = EncryptUtil.MD5StringTo32Bit(iDownload.getITag(), true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!TextUtils.isEmpty(unCompletedFile)) {
                    File file = new File(DownloadUtils.DOWNLOAD_FILEDIR, unCompletedFile);
                    if (file.exists() && file.isFile()) {
                        // 已经下载了.
                        downloadFileInfoInit.setSaveFileNameEncrypt(unCompletedFile);
                    }
                }
                //将新建的下载信息放入到下载的Listenre 中去
                DownloadUtils.getSingleton().putDownloadFileInfo(iDownload.getITag(), downloadFileInfoInit);
            }
            //重新取一遍
            downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag());
            if (downloadFileInfo == null) return;
            //为当前的下载添加listener
            downloadFileInfo.addViewCallback(this);

            ProgressCallback progressCallback = downloadFileInfo.getProgressCallback();
            List<OnDownloadingCallback> viewCallbackList = downloadFileInfo.getViewCallbackList();
            if (DownloadStatus.INIT.equals(downloadFileInfo.getDownloadStatus())) {
                //初始状态,又分为三种,一种是 未曾下载过.这个时候不走这个逻辑,因为downloadFileInfo = null

                String saveFileDir = downloadFileInfo.getSaveFileDir();
                String saveFileName = downloadFileInfo.getSaveFileName();
                //一种是 已经下载完成,需要去安装
                //判断 本地文件中是否有完整apk
                File gameApk = new File(saveFileDir, saveFileName);
                if (gameApk.exists() && gameApk.isFile()) {
                    ViewSet(INSTALL, 0);
                    return;
                }

                //一种是上次启动app 的时候下过
                //获取本地的记录
                String saveFileNameEncrypt = downloadFileInfo.getSaveFileNameEncrypt();
                if (TextUtils.isEmpty(saveFileNameEncrypt)) {
                    ViewSet(INIT, 0);
                } else {
                    long apkTotalSize = AppUtils.get(saveFileNameEncrypt, 0L);//当前apk 总下载量
                    long completedSize = 0L;
                    File file = new File(saveFileDir, saveFileNameEncrypt);
                    if (file.exists() && file.isFile()) {
                        completedSize = file.length();
                    }
                    if (apkTotalSize > 0L && completedSize > 0L) {
                        //现在证明有本地的下载记录的
                        ViewSet(PAUSE, (int) ((completedSize * 100) / apkTotalSize));
                        downloadFileInfo.setPercent((int) ((completedSize * 100) / apkTotalSize));
                    }
                }

            } else {
                if (DownloadStatus.PREPAREING.equals(downloadFileInfo.getDownloadStatus())) {
                    //准备下载中,正在请求接口,还未返回
//                    ViewSet(PREPAREING,0);
                    ViewSet(PREPAREING, downloadFileInfo.getPercent());
                } else if (DownloadStatus.DOWNLOADING.equals(downloadFileInfo.getDownloadStatus())) {
                    //正在下载中,先获取当前的下载进度,然后设置上,由于有callback的原因,在进度走的时候  这个View 也会走
                    ViewSet(DOWNLOADING, downloadFileInfo.getPercent());
                } else if (DownloadStatus.PAUSE.equals(downloadFileInfo.getDownloadStatus())) {
                    //暂停中
                    ViewSet(PAUSE, downloadFileInfo.getPercent());
                } else if (DownloadStatus.COMPLETED.equals(downloadFileInfo.getDownloadStatus())) {
                    //下载完成
                    ViewSet(INSTALL, 100);
                }
            }
        }

    }


    /**
     * 取消下载的后续操作,
     *
     * @param info
     * @param downloadFileInfoTemp
     */
    private void cancelAfterOpration(HttpInfo info, DownloadFileInfo downloadFileInfoTemp) {
        OkHttpUtil.getDefault().cancelRequest(OkHttpUtil.getTag(info.getUrl()));
        if (!TextUtils.isEmpty(downloadFileInfoTemp.getSaveFileNameEncrypt())) {
            String saveFileNameEncrypt = downloadFileInfoTemp.getSaveFileNameEncrypt();
            AppUtils.remove(saveFileNameEncrypt);
            DownUpLoadHelper.removeTask(saveFileNameEncrypt);
            downloadFileInfoTemp.setSaveFileNameEncrypt("");
            downloadFileInfoTemp.setDownloadStatus(DownloadStatus.INIT);
            try {
                String s = EncryptUtil.MD5StringTo32Bit(OkHttpUtil.getTag(info.getUrl()), true);
                File file = new File(downloadFileInfoTemp.getSaveFileDir() + s);
                if (file.exists() && file.isFile()) {
                    boolean delete = file.delete();
//                    LogUtils.e("gzq", "delete = " + file.toString() + "  " + delete);
                }
                File gameFile = new File(downloadFileInfoTemp.getSaveFileDir() + downloadFileInfoTemp.getSaveFileName() + ".apk");
                if (gameFile.exists() && gameFile.isFile()) {
                    boolean delete = gameFile.delete();
//                    LogUtils.e("gzq", "delete = " + gameFile.toString() + "  " + delete);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        LiveEventBus.get(Config.EventBus.gameDownLoad, HashMap.class).removeObserver(observer);
//        if (iDownload != null) {
//            DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag());
//            if (downloadFileInfo != null) {
//                downloadFileInfo.removeViewCallback(this);
//            }
//        }
    }


    private int INIT = 1;
    private int PREPAREING = 2;
    private int DOWNLOADING = 3;
    private int PAUSE = 4;
    private int OPEN = 6;
    private int INSTALL = 7;
    private int NoExist = 8;

    /**
     * 展示当前View 的表现形式
     *
     * @param viewCode
     * @param percent
     */
    private void ViewSet(int viewCode, float percent) {

        if (viewCode == INIT) {
            prompt.setText(download);
            progress.setProgress(0);
            if (progress.getVisibility() == View.VISIBLE) {
                progress.setVisibility(View.INVISIBLE);
            }

            if (bgDefault != 0) {
                container.setBackgroundResource(bgDefault);
            }
            if (textColorDefault != 0) {
                prompt.setTextColor(textColorDefault);
            }

        } else if (viewCode == PREPAREING) {
            prompt.setText(prepareing);
            progress.setProgress((int) percent);
            if (progress.getVisibility() == View.INVISIBLE) {
                progress.setVisibility(View.VISIBLE);
            }

            container.setBackgroundResource(0);
            if (textColorLoading != 0) {
                prompt.setTextColor(textColorLoading);
            }

        } else if (viewCode == DOWNLOADING) {
            prompt.setText(percent + "%");
            progress.setProgress((int) percent);
            if (progress.getVisibility() == View.INVISIBLE) {
                progress.setVisibility(View.VISIBLE);
            }
            container.setBackgroundResource(0);
            if (textColorLoading != 0 && prompt.getCurrentTextColor() != textColorLoading) {
                prompt.setTextColor(textColorLoading);
            }
        } else if (viewCode == PAUSE) {
            prompt.setText(continues);
            progress.setProgress((int) percent);
            if (progress.getVisibility() == View.INVISIBLE) {
                progress.setVisibility(View.VISIBLE);
            }
            container.setBackgroundResource(0);

            if (textColorLoading != 0 && prompt.getCurrentTextColor() != textColorLoading) {
                prompt.setTextColor(textColorLoading);
            }

        } else if (viewCode == OPEN) {

            prompt.setText(open);
            if (progress.getVisibility() == View.VISIBLE) {
                progress.setVisibility(View.INVISIBLE);
            }

            if (bgComplete != 0) {

                container.setBackgroundResource(bgComplete);
            }
            if (textColorComplete != 0) {
                prompt.setTextColor(textColorComplete);
            }
        } else if (viewCode == INSTALL) {
            prompt.setText(install);
            if (progress.getVisibility() == View.VISIBLE) {
                progress.setVisibility(View.INVISIBLE);
            }
            if (bgComplete != 0) {
                container.setBackgroundResource(bgComplete);
            }
            if (textColorComplete != 0) {
                prompt.setTextColor(textColorComplete);
            }
        } else if (viewCode == NoExist) {
            prompt.setText(noExist);
            progress.setProgress(0);

            if (bgComplete != 0) {
                container.setBackgroundResource(bgComplete);
            }
            if (textColorComplete != 0) {
                prompt.setTextColor(ColorUtils.getColor(R.color.color999));
            }
            setOnClickListener(null);
        } else {
            prompt.setText(download);
            progress.setProgress(0);
            if (bgDefault != 0) {
                container.setBackgroundResource(bgDefault);
            }
            if (textColorDefault != 0) {
                prompt.setTextColor(textColorDefault);
            }
        }

    }


    /**
     * 所有的回调都要  tag 匹配才行
     */

    @Override
    public String getViewTag() {
        if (iDownload != null) {
            return iDownload.getITag();
        }
        return "";
    }

    @Override
    public void onInit(String tag) {
        if (iDownload != null && TextUtils.equals(tag, iDownload.getITag())) {
            ViewSet(INIT, 0);
        }
    }

    @Override
    public void onPrepareing(String tag) {
//        Log.e("gzq", ""+ TextUtils.equals(tag,iDownload.getITag()) + " "+(DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag()) != null));
        if (iDownload != null && TextUtils.equals(tag, iDownload.getITag()) && DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag()) != null) {
            ViewSet(PREPAREING, DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag()).getPercent());
        }
    }

    @Override
    public void onLoading(String tag, float percent) {
        this.percent = percent;
        if (iDownload != null && TextUtils.equals(tag, iDownload.getITag())) {
//            LogUtils.e("onLoading", "正在下载onLoading->" + tag + "   " + percent);
            ViewSet(DOWNLOADING, percent);
            DownloadAgainUtils.showNotification(getContext(), iDownload, (int) percent);
        }
    }

    @Override
    public void onPause(String tag, float percent) {
        if (iDownload != null && TextUtils.equals(tag, iDownload.getITag())) {
            ViewSet(PAUSE, percent);
        }
    }

    @Override
    public void onComlpeted(String tag, HttpInfo info) {
        if (iDownload != null && TextUtils.equals(tag, iDownload.getITag())) {
            NewsDBUtil.getInstance().addGameState(iDownload.getIGameId());
            DownloadAgainUtils.getManager().cancel(Long.valueOf(iDownload.getIGameId()).intValue());
            DownloadUtils.getSingleton().removeDownloadFileInfo(tag);
            ViewSet(INSTALL, 100);
            DownloadUtils.getSingleton().putInstallCallBack(iDownload.getIPackageName(), this);
            DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(tag);
            if (downloadFileInfo != null && !TextUtils.isEmpty(downloadFileInfo.getSaveFileNameEncrypt())) {
                AppUtils.remove(downloadFileInfo.getSaveFileNameEncrypt());
            }

            if (eventData != null) {
                MobclickAgentUtils.event(UmEventId.game_downloadsuccess, eventData);
            }
//            //下载完成统计
//            DownloadUtils.getSingleton().requestStatisticsInterface(iDownload.getIGameId(), DownloadUtils.CLICKTYPE_DOWNLOADCOMPLETED);
            AppUtils.installAPP(AppApplication.getInstance(), new File(info.getRetDetail()));
        }
    }

    @Override
    public void onInstalled(String tag) {
        if (iDownload != null && TextUtils.equals(tag, iDownload.getIPackageName())) {
            ViewSet(OPEN, 0);
        }
    }

    @Override
    public void onClick(View v) {
        try {


            //点击 分为三种
            //1.已经安装了,开启游戏
            boolean isinstall = com.blankj.utilcode.util.AppUtils.isAppInstalled(iDownload.getIPackageName());
            //统计的 点击名,用来区分 游戏详情的点击还是列表的点击
            Object tag = getTag(R.id.tag_four);
            String name = "";
            if (tag != null) {
                name = tag.toString();
            }
            if (isinstall) {//已经安装过了-可以直接打开
                AppUtils.startUpApp(getContext(), iDownload.getIPackageName());
                //启动游戏的统计
                DownloadUtils.getSingleton().requestStatisticsInterface(iDownload.getIGameId(), DownloadUtils.CLICKTYPE_STARTUP);
                MobclickAgentUtils.event(Config.EventBauduId.game_065, name + "点击启动游戏");
                StatService.onEvent(AppApplication.getInstance(), "065", name + "点击启动游戏", 1);

            } else {//没有安装_去安装
                File unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, iDownload.getIPath() + ".apk");

                if (unInstallFile.exists() && unInstallFile.isFile()) {//安装游戏

                    AppUtils.installAPP(getContext(), unInstallFile);
                    MobclickAgentUtils.event(Config.EventBauduId.game_065, name + "点击安装游戏");
                    StatService.onEvent(AppApplication.getInstance(), "065", name + "点击安装游戏", 1);
                } else {//继续下载/开始下载
                    if (TextUtils.isEmpty(iDownload.getIUrl())) {
                        ToastUtils.makeText("下载地址为空");
                        return;
                    }
                    DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(iDownload.getITag());
                    LogUtils.e("LoadingView", downloadFileInfo);
                    if (downloadFileInfo != null) {
                        downloadFileInfo.addViewCallback(this);
                        String saveFileNameEncrypt = downloadFileInfo.getSaveFileNameEncrypt();
                        if (TextUtils.isEmpty(saveFileNameEncrypt)) {//证明是第一次下载
                            //第一次下载的统计
                            gameDownload();
                            requestInstallPermission();
                            DownloadUtils.getSingleton().requestStatisticsInterface(iDownload.getIGameId(), DownloadUtils.CLICKTYPE_DOWNLOAD);
                            if (eventData != null) {
                                MobclickAgentUtils.event(UmEventId.game_download, eventData);
                            }
                            MobclickAgentUtils.event(Config.EventBauduId.game_065, name + "点击下载游戏");
                            StatService.onEvent(AppApplication.getInstance(), "065", name + "点击下载游戏", 1);
                            DownloadUtils.DOWN_LOAD_COUNT++;
                            //在排行榜当前页面的时候显示小红点
                            Bundle bundle = new Bundle();
                            bundle.putInt("down", 333);
                            EventBus.getDefault().post(bundle);
                            //插入到数据库中
                            GameDownloadActivity.insertGame(iDownload.getIGameId(), iDownload.getITitle(), iDownload.getIUrl(), iDownload.getIAppIcon(),
                                    iDownload.getIGameSummary(), iDownload.getIPackageName(), iDownload.getIPath(), iDownload.getISize());

                        } else {
                            File file = new File(DownloadUtils.DOWNLOAD_FILEDIR, saveFileNameEncrypt);
                            if (file.exists() && file.isFile()) {
                                // 已经下载了.
                            } else {
                                //第一次下载的统计
                                gameDownload();
                                requestInstallPermission();
                                DownloadUtils.getSingleton().requestStatisticsInterface(iDownload.getIGameId(), DownloadUtils.CLICKTYPE_DOWNLOAD);
                                if (eventData != null) {
                                    MobclickAgentUtils.event(UmEventId.game_download, eventData);
                                }
                                MobclickAgentUtils.event(Config.EventBauduId.game_065, name + "点击下载游戏");
                                StatService.onEvent(AppApplication.getInstance(), "065", name + "点击下载游戏", 1);
                                DownloadUtils.DOWN_LOAD_COUNT++;
                                //在排行榜当前页面的时候显示小红点
                                Bundle bundle = new Bundle();
                                bundle.putInt("down", 333);
                                EventBus.getDefault().post(bundle);
                                //插入到数据库中
                                GameDownloadActivity.insertGame(iDownload.getIGameId(), iDownload.getITitle(), iDownload.getIUrl(), iDownload.getIAppIcon(),
                                        iDownload.getIGameSummary(), iDownload.getIPackageName(), iDownload.getIPath(), iDownload.getISize());
                            }
                        }
                        //下载
                        DownloadUtils.getSingleton().down(iDownload.getIUrl(), iDownload.getIPath());
                    } else {
                        ToastUtils.makeText("下载信息获取失败");
                    }
                }
            }
        } catch (Exception e) {

        }
    }

    private void requestInstallPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先判断是否有安装未知来源应用的权限
            boolean haveInstallPermission = getContext().getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                //弹框提示用户手动打开
                DialogUtils.showTwoBtnDialog("迷彩虎需要获得允许安装未知来源应用权限，用于为你安装和更新游戏应用。", "去授权", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                //此方法需要API>=26才能使用
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                AvoidOnResultHelper.startActivityForResult((FragmentActivity) ActivityUtils.getTopActivity(), intent, new AvoidOnResultHelper.ActivityCallback() {
                                    @Override
                                    public void onActivityResult(int resultCode, Intent data) {
                                        if (resultCode == RESULT_OK) {
                                        }
                                    }
                                });
                            }
                        } catch (Exception e) {

                        }
                    }
                });
//                return;
            }
        }
    }

    private HashMap<String, Object> eventData;

    public void setEventData(HashMap<String, Object> eventData) {
        this.eventData = eventData;
    }


    private void gameDownload() {
        HashMap<String, String> parmsMap = new HashMap<String, String>();
        if (UserInforManager.getInstance().isLogin()) {
            parmsMap.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        }
        HttpListener<DataBean<GetTaskBean>> httpListener = new HttpListener<DataBean<GetTaskBean>>() {

            @Override
            public void onStart() {
            }

            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<GetTaskBean> response) {
                if (response != null && response.noError()) {
                    GetTaskBean data = response.getData();
                    if (data != null) {
                        boolean isGetTask = data.getIsGetTask("下载游戏");
                    }
                }
            }
        };
        //请求网络
        HttpUtils.addPostCacheRequest(URIContant.GAME_DOWNLOAD_TASK, new TypeToken<DataBean<GetTaskBean>>() {
        }.getType(), "loadView", parmsMap, httpListener);
    }

}
